package org.martin.snsrs.client.services.http;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.martin.snsrs.client.manager.Session;

import dalvik.system.BaseDexClassLoader;

import android.content.Context;

public class Api {
	private static final String DEFAULT_BASE_URL="http://192.168.0.107:8080/SnsRS/";
	
	private Context context;
	
	private String sessionKey;
	
	private HttpClient client;
	
	private String baseURL;
	
	public Api(Context context){
		this.context = context;
		Session session = Session.get(context);
		client = HttpClientUtils.getHttpClient();
		HttpClientUtils.setTimeout(client, 20000);
		if(session != null){
			sessionKey = session.sessionKey;
		}
		baseURL = DEFAULT_BASE_URL;
	}
	
	public String getURL(String method, Map<String, String> params){
		String url = "";
		if(sessionKey != null)
			params.put("sessionKey", sessionKey);
		url += baseURL + method + "?";
		Iterator<Entry<String, String>> itor = params.entrySet().iterator();
		while(itor.hasNext()){
			Map.Entry<String, String> entry = itor.next();
			try {
				url +=entry.getKey() + "=" + URLEncoder.encode(entry.getValue(), "UTF-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			if(itor.hasNext())
				url += "&";
		}
		return url;
	}
	
	public JSONObject get(String requestURL) throws Exception{
		HttpGet request = new HttpGet(requestURL);
		HttpResponse response = client.execute(request);
		return parseResponse(response);
	}
	
	public JSONObject post(String requestURL, RequestParams params) throws Exception{
		HttpPost post = new HttpPost(requestURL);
		if(params != null)
			post.setEntity(params.getEntity());
		return parseResponse(client.execute(post));
		
	}
	
	public JSONObject parseResponse(HttpResponse response) throws Exception{
		int status = response.getStatusLine().getStatusCode();
		JSONObject result = null;
		if(status > 300)
			return null;
		HttpEntity entity = response.getEntity();
		if(entity != null){
			BufferedHttpEntity bufferEntity = new BufferedHttpEntity(entity);
			String str = EntityUtils.toString(bufferEntity);
			result = new JSONObject(str);
		}
		return result;
	}
}
